package org.apache.mina.example.lily.service;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

public class ServerDecoder extends ProtocolDecoderAdapter {

	private Charset charset;

	public ServerDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		System.out.println(11);
		Integer length = (Integer)session.getAttribute("length");
		if(length==null){
			length = in.getInt();
			session.setAttribute("length", length);
		}
		
		CharsetDecoder decoder = (CharsetDecoder)session.getAttribute("charsetdecoder");
		if(decoder == null){
			decoder = charset.newDecoder();
			session.setAttribute("charsetdecoder", decoder);
		}
		
		IoBuffer data = (IoBuffer)session.getAttribute("data");
		
		if(data==null){
			if(length<=in.remaining()){
				String json = in.getString(length, decoder);
				System.out.println(json);
				HttpRequestBean bean = JSON.parseObject(json,HttpRequestBean.class);
				out.write(bean);
				session.removeAttribute("length");
				return;
			}else{
				data = IoBuffer.allocate(length);
				data.put(in.buf());
				session.setAttribute("data");
			}
		}else{
			if(length<=in.remaining()+data.capacity()){
				String json = data.put(in).getString(length,decoder);
				JSONObject jsonObject = JSON.parseObject(json);
				out.write(jsonObject);
				session.removeAttribute("length");
				session.removeAttribute("data");
				return;
			}else{
				data.put(in);
			}
		}
		in.flip();
	}
}
